package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import me.yokeyword.fragmentation.SupportFragment;

public class MainFragment extends SupportFragment {

    private SupportFragment[] mFragments = new SupportFragment[1];
    public static final int FIRST = 0;
    public int prePosition = 0;


    public static MainFragment newInstance() {

        Bundle args = new Bundle();

        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        initView(view);

        return view;
    }

    private void initView(View view) {
        EventBus.getDefault().register(this);

    }
    //在activity被创建时,加载fragment
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SupportFragment firstFragment = findChildFragment(HomeFragment.class);
        if (firstFragment==null){

            mFragments[FIRST] = HomeFragment_xiugaione.newInstance();  //首页

            loadMultipleRootFragment(R.id.fl_tab_container, FIRST,
                    mFragments[FIRST]);
        }else{
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用,也可以通过getChildFragmentManager.findFragmentByTag自行进行判断查找(效率更高些),用下面的方法查找更方便些
            mFragments[FIRST] = firstFragment;

        }

    }

    //类似onActivityResault()
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);

    }


    @Subscribe
    public void startNewFragment(StartNewFragmentEvent event) {
        if (!event.targetFragment.isAdded()) {
        start(event.targetFragment);
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();

    }


}
